package com.zzyl.common.utils;

import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;


public class AgeCalculator {

    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");


    public static int calculateAge(String birthDate) throws DateTimeParseException {
        LocalDate birth = LocalDate.parse(birthDate, DATE_FORMATTER);
        LocalDate now = LocalDate.now();
        return Period.between(birth, now).getYears();
    }


    public static Period calculateDetailedAge(String birthDate) throws DateTimeParseException {
        LocalDate birth = LocalDate.parse(birthDate, DATE_FORMATTER);
        LocalDate now = LocalDate.now();
        return Period.between(birth, now);
    }


    public static String getFormattedAge(String birthDate) {
        try {
            Period period = calculateDetailedAge(birthDate);
            return String.format("%d岁%d个月%d天", 
                period.getYears(), 
                period.getMonths(), 
                period.getDays());
        } catch (DateTimeParseException e) {
            return "无效的日期格式，请使用yyyy-MM-dd格式";
        }
    }

    // 示例用法
    public static void main(String[] args) {
        String birthDate = "1990-05-15";
        
        // 简单年龄计算
        int age = calculateAge(birthDate);
        System.out.println("年龄: " + age + "岁");
        
        // 详细年龄信息
        Period detailedAge = calculateDetailedAge(birthDate);
        System.out.println("详细年龄: " + 
            detailedAge.getYears() + "年" +
            detailedAge.getMonths() + "个月" +
            detailedAge.getDays() + "天");
        
        // 格式化输出
        System.out.println("格式化年龄: " + getFormattedAge(birthDate));
    }
}